// 退出事件
const onLogout = function () {
    const logout = document.querySelector('.logout')
    logout.addEventListener('click', function () {
        // alert('你好啊')
        location.href = './login.html'
    })
}

// 动态显用户信息
const showUserInfo = function () {
    let user = localStorage.getItem('user') 
    user = JSON.parse((user))
    console.log(user);
    let userinfoStr = `${user.username}`

    userinfoStr = userinfoStr.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2');
    const userinfo = document.querySelector('.userinfo')
    userinfo.innerHTML = userinfoStr
}

// 动态显示回到顶部显示框
// 获取滚动条距离顶部距离
function backTop() {
    const backEle = document.querySelector('.back')    
    window.onscroll = function () {
        let scrol = window.scrollY
        // console.log(scrol);
        if (scrol == 0) {
            backEle.style.display = 'none'
        } else {
            backEle.style.display = 'block'
        }
    }
    backEle.addEventListener('click', function () {

        let time = setInterval(function () {
            let sctop = document.documentElement.scrollTop
            // console.log('距离：', sctop);
            let s = 50
            if (sctop > s) {
                document.documentElement.scrollTop = sctop - s
            } else {
                document.documentElement.scrollTop = 0
            }
            if (sctop <= 0) {
                clearInterval(time)
            }
        }, 50)   
    })
}

// 定义空数组，装所有的数据
let productList = []

const getProductList = async function () {
    let res = await myAxios({
        method: 'get',
        url:'/products/product',
    })
    let { code, list } = res.data
    if (code == 1) {
        let productList = list
        showProductList(productList)
    }
}

// 动态渲染商品列表
function showProductList(productList = []) {
    let lists = productList.map(item => {
        return `<div class = "product" onclick="onDetail(${item.id})">
        <a href="javascript:void(0)"><img src="${item.image}" ail=""></a>
        <p>${item.title}</p>
        <div class="one">
        <div>天猫</div><span>包邮<span>
        </div>
        <div class="two"><span>￥<big>${item.originPrice}</big></span>
        ${item.saleNum} 人已买<a href="">${item.price}元卷</a></div>
        </div>`
    }).join('')
    const productlists = document.querySelector('.productlist')
    productlists.innerHTML = lists
    console.log(lists);
}
// 跳转详情页
function onDetail(id) {
    location.href = './detail.html?id=' + id
}
getProductList()
backTop()

